<template>
  <div class="casePage">
    <el-row>
      <el-col :span="5">
        <TreeNavigation :tree-data.sync="dirTreeData" @chooseDirId="getBizId" @getDirList="getDirList"
                        :productLineId="$route.params.productLineId" :total="caseNum"
        ></TreeNavigation>
      </el-col>
      <el-col :span="19">
        <div style="position: relative; top: 10px; left: 20px">
          <div style="position: relative; top: 10px;">
            <span>
              <el-button type="primary" icon="el-icon-medal" @click="caseFilterDialog">筛选</el-button>
              <CaseFilter ref="caseFilter" :creators="productMember" @filterCondition="getFilterCondition"></CaseFilter>
            </span>
            <span style="position: relative; left: 20px;">
              <el-button type="primary" icon="el-icon-plus" @click="addSuiteDialog"> 新建用例集 </el-button>
              <CaseModal ref="addSuite" :operate="addTestSuite" :title="addTitle"></CaseModal>
            </span>
          </div>
          <div style="position: relative; top: 30px;">
            <el-table
              max-height = 700
              highlight-current-row
              ref="caseListTable"
              :data="caseListData"
              stripe
              resizable
              border
              style="width: 100%"
              :row-key="getRowKey"
              @row-click="handleRowClick"
              :expand-row-keys="expands"
              @expand-change="expandChange">
              <el-table-column type="expand" >
                <template slot-scope="scope_item">
                  <el-table
                    :data="scope_item.row.recordList"
                    border
                    style="width: 100%">
                    <el-table-column
                      label="任务ID"
                      width="100">
                      <template slot-scope="scope">
                        <span>{{scope.row.recordId}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="任务名称"
                      width="120">
                      <template slot-scope="scope">
                        <span style="color: #409EFF"
                          v-if="scope.row.taskExecUrl !== undefined && scope.row.taskExecUrl.length >=1" >
                          <a :href="scope.row.taskExecUrl" target="_self">{{scope.row.title}}</a>
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="负责人"
                      width="120">
                      <template slot-scope="scope">
                        <span>{{scope.row.owner}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="执行人"
                      width="120">
                      <template slot-scope="scope">
                        <span>{{scope.row.executors}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="通过率"
                      width="100">
                      <template slot-scope="scope">
                        <span>{{scope.row.successRate}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="execNum"
                      label="已测用例"
                      width="100">
                      <template slot-scope="scope">
                        <span>{{scope.row.execNum}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="expectTime"
                      label="期望时间"
                      min-width="200"
                      width="200">
                      <template slot-scope="scope">
                        <span v-if="scope.row.showExpectTime">{{scope.row.expectStartTime}} 至 {{scope.row.expectEndTime}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <CreateTask ref="editTask" :title="editTestTask"  @getRecordList="getRecordList"
                                    :case-id="caseId" :task-list-data="taskListData">
                        </CreateTask>
                        <el-button
                          size="mini"
                          @click="execTask(scope.$index, scope.row)">执行</el-button>
                        <el-button
                          size="mini"
                          @click="editTaskDialog(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                          size="mini"
                          type="danger"
                          @click="delete_task(scope.$index, scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column
                prop="id"
                label="用例集ID"
                width="100">
              </el-table-column>
              <el-table-column
                prop="title"
                label="用例集名称"
                width="180">
                <template slot-scope="scope_suite">
                  <span style="color: #409EFF"
                    v-if="scope_suite.row.caseEditUrl!== undefined && scope_suite.row.caseEditUrl.length >=1">
                    <a :href="scope_suite.row.caseEditUrl">{{ scope_suite.row.title }}</a>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="requirementId"
                label="关联需求"
                width="140">
              </el-table-column>
              <el-table-column
                prop="modifier"
                label="最近更新人"
                width="140">
              </el-table-column>
              <el-table-column
                prop="creator"
                label="创建人"
                width="140">
              </el-table-column>
              <el-table-column
                prop="gmtCreated"
                label="创建时间"
                width="180"
                :formatter="dateFormatYmdHMS">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-row :gutter="10">
                    <el-col :span="40">
                      <span>
                        <el-button
                          size="mini" class="operate-button"
                          @click="editSuiteDialog(scope.$index, scope.row)"> 编辑
                      </el-button>
                      </span>
                    </el-col>
                    <el-col :span="40">
                      <span>
                        <el-button
                          size="mini" class="operate-button"
                          @click="copySuiteDialog(scope.$index, scope.row)"> 复制
                        </el-button>
                        <CaseModal ref="copySuite" :title="copyTitle" :operate="copyTestSuite" @getDirList="getDirList"></CaseModal>
                      </span>
                  </el-col>
                  <el-col :span="100">
                    <span>
                      <el-button
                          size="mini" class="operate-button"
                          @click="createTaskDialog(scope.$index, scope.row)"> 建任务
                      </el-button>
                      <CreateTask ref="createTask" :title="addTestTask" @getRecordList="getRecordList"
                                  :case-id="caseId"> <i class="el-icon-s-operation el-icon--right"></i>
                      </CreateTask>
                    </span>
                  </el-col>
                  <el-col :span="100">
                    <span>
                      <el-dropdown size="mini">
                        <span class="el-dropdown-link">
                           <i class="el-icon-more el-icon--right" style="color: #409EFF;"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item  @click.native="show_history(scope.row)" style="font-size: 15px">历史版本</el-dropdown-item>
                          <el-dropdown-item  v-down-load-url="load_xmind(scope.row)" style="font-size: 15px">导出xmind</el-dropdown-item>
                          <el-dropdown-item  @click.native="delete_cases(scope.$index, scope.row)" style="font-size: 15px">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </span>
                  </el-col>
                </el-row>
                </template>
                <CaseModal ref="editSuite"
                           :title="editTitle"
                           :operate="editTestSuite"
                           @getCaseList="getCaseList">
                </CaseModal>
              </el-table-column>
            </el-table>
          </div>
          <div style="position: relative; left: 30px; top: 50px;">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page="pageNum"
              :total="caseNum"
              :hide-on-single-page="true"
              @current-change="handlePageChange">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import CreateTask from '@/components/case/caselist/CreateTask'
import TreeNavigation from '@/components/case/caselist/TreeNavigation'
import CaseModal from "@/components/case/caselist/CaseModal"
import CaseFilter from '@/components/case/caselist/CaseFilter'
import {dateFormatYmd} from "@/views/casepage/DateFormat";
import request from '@/utils/axios'
export default {
  name: 'CasePage',
  components: {
    CaseModal,
    CreateTask,
    TreeNavigation,
    CaseFilter
  },
  data() {
    return {
      addTestSuite:'add',
      addTitle: '新建用例集',
      editTestSuite:'edit',
      editTitle: '编辑用例集',
      copyTestSuite:'copy',
      copyTitle: '复制用例集',
      addTestTask: '创建测试任务',
      editTestTask: '编辑测试任务',
      form: {
        nme: '',
        person: '',
        story: '',
        keywd: '',
        fdate: ''
      },
      dialogFormVisible1: false,
      productMember: [],
      bizId: ['root'],
      dirTreeData: [],
      caseListData: [],
      taskListData: [],
      expands: [],
      caseId: 0,
      caseNum: 0,
      pageNum: 1,
      historyLink: '',
      getRowKey(row) {
        return row.id
      }
    }
  },
  methods: {
    dateFormatYmdHMS: function (row, column, cellValue, index) {
      const dateRc = row[column.property]
      if (dateRc != null) {
        const date = new Date(dateRc)
        let year = date.getFullYear()
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
        let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
        let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
        let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
        let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
      }
    },
    handleRowClick: function (row, index, e) {
      if (index.label !== '操作' && index.label !== '用例集名称') {
        this.$refs.caseListTable.toggleRowExpansion(row)
      }
    },
    async expandChange(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = []
        if (row) {
          this.caseId = row.id
          this.expands.push(row.id)//只展开当前行id
          this.getRecordList(row.id)
        } else {
          this.expands = []
        }
      }
    },
    show_history(row) {
      this.$router.push('/case/versions/history/' + row.id)
    },
    load_xmind(row) {
      let url= `/file/export?id=${row.id}`
      return {url: url, name: row.title + '.xmind'}
    },
    getBizId: function (data) {
      this.bizId = data? data.id: 'root'
      this.pageNum = 1
      console.log('get dir id', data)
      this.getCaseList()
    },
    getFilterCondition: function (filterCondition) {
      const nameFilter = filterCondition.nameFilter
      const createrFilter = filterCondition.createrFilter
      const storyFilter = filterCondition.storyFilter
      const caseKeyWords = filterCondition.caseKeyWords
      const choiseDate = filterCondition.choiseDate
      this.getCaseList(nameFilter, createrFilter,storyFilter, choiseDate, caseKeyWords)
    },
    getCaseList: function (
      nameFilter,
      createrFilter,
      storyFilter,
      choiseDate = [],
      caseKeyWords = '',
    ) {
      let url = '/case/list'
      request(url, {
        method: 'GET',
        params: {
          productLineId: this.$route.params.productLineId,
          pageSize: 10,
          pageNum: this.pageNum? this.pageNum: 1,
          caseType: 0,
          title: nameFilter || '',
          creator: createrFilter || '',
          channel: 1,
          requirementId: storyFilter || '',
          beginTime: choiseDate.length > 0 ? `${choiseDate[0]} 00:00:00` : '',
          endTime: choiseDate.length > 0 ? `${choiseDate[1]}  23:59:59` : '',
          bizId: this.bizId ? this.bizId : 'root',
          caseKeyWords: caseKeyWords || '',
        },
      }).then(res => {
        if (res.code === 200) {
          res.data.dataSources.forEach(item => {
            item.recordList = [];
            item.caseEditUrl = '/case/edit/1/' + item.id
          })
          this.caseListData = res.data.dataSources? res.data.dataSources :[];
          this.caseNum = res.data.total? res.data.total:0
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      });
    },
    getRecordList: function (caseId) {
      let url = '/record/list';
      request(url, { method: 'GET', params: { caseId: caseId } }).then(res => {
        if (res.code === 200) {
          const taskListData = res.data.map(item => {
            item['successRate'] = (Number(item.successNum) / Number(item.totalNum)*100).toFixed(2) + '%';
            item['execNum'] = String(item.executeNum) +'/' +String(item.totalNum)
            item['taskExecUrl'] = '/case/edit/' + this.$route.params.productLineId +'/' + caseId +'/' + item.recordId;
            if (item.expectStartTime && item.expectEndTime) {
              item.showExpectTime = true
              item.expectStartTime = dateFormatYmd(item.expectStartTime)
              item.expectEndTime = dateFormatYmd(item.expectEndTime)
            }
            return item
          });
          this.taskListData = taskListData
          this.caseListData.map(item => {
            if (item.id === caseId) {
              item.recordList = taskListData;
              item.recordNum = taskListData.length;
              return item
            }
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    getCreators: function () {
      let url = '/case/listCreators'
      request(url, {
        method: 'GET',
        params: { productLineId: this.$route.params.productLineId, caseType: 0 },
      }).then(res => {
        // console.log(res.data);
        if (res.code === 200) {
          this.productMember = res.data;
          console.log('creators: ', res.data)
        }
      });
    },
    getDirList: function () {
      let url = '/dir/list'
      request(url, {
        method: 'GET',
        params: {
          productLineId: this.$route.params.productLineId,
          channel: 1
        },
      }).then(res => {
        // console.log(res.data);
        if (res.code === 200) {
          let dirData = res.data.children;
          this.dirTreeData = this.addTreeAttribute(dirData);
          console.log('dirTreeData: ', this.dirTreeData)
        }
      });
      this.getCaseList();
    },
    addTreeAttribute(data){  // tree结构递归添加属性
      for (let i = 0; i < data.length; i++) {
        data[i].allowRename = false
        data[i].isEdit = false
        data[i].icon = "el-icon-folder-opened"
        if (data[i].children&&data[i].children.length > 0) {
          this.addTreeAttribute(data[i].children)
        }
      }
      return data
    },
    delete_cases(index, row) {
      let proj_name = ''
      let task_num= 0
      this.caseListData.forEach(item => {
        if (row.id === item.id) {
          proj_name = item.title
          task_num = item.recordNum
        }
      })
      this.$confirm('当前正在删除 '+proj_name+' 用例集，并且删除用例集包含的'+task_num+'个测试任务与测试结果等信息，此操作不可撤销。', '确认删除用例集吗', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        let url = '/case/delete'
        request(url, {
          method: 'POST',
          body: {
            id: row.id
          }
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getDirList()
            this.getCaseList()
          }
          else {
            this.$message({
              type: 'error',
              message: '删除异常!'
            });
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '接口调用异常!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    delete_task(index, row) {
      this.$confirm('这将删除该测试任务下所有的测试与测试结果等信息，并且不可撤销。', '确认删除测试任务吗', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        let url = `/record/delete`
        request( url, {
          method: 'POST',
          body: {
            id: row.id
          }
        }).then (res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getRecordList(this.caseId)
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '接口调用异常'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addSuiteDialog() {
      this.$refs.addSuite.showDialog()
    },
    caseFilterDialog() {
      this.$refs.caseFilter.showDialog()
    },
    editSuiteDialog(index, row) {
      this.$refs.editSuite.showDialog(index, row)
    },
    copySuiteDialog(index, row) {
      this.$refs.copySuite.showDialog(index, row)
    },
    createTaskDialog(index, row) {
      this.caseId = row.id
      this.$refs.createTask.showDialog(index, row)
    },
    editTaskDialog(index, row) {
      this.$refs.editTask.showDialog(index, row)
    },
    execTask(index, row) {
      this.$router.replace(row.taskExecUrl)
    },
    handlePageChange: function (val) {
      this.pageNum = val
      this.getCaseList()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getCreators();
      this.getDirList();
      // this.getCaseList();
    })
  }
}

</script>

<style lang="less" scoped>
.operate-button {
  min-width: 50px;
  height: 30px;
  padding: 0;
  color: #409EFF;
  /deep/ i {
    font-size: 16px;
  }
}
</style>
